package top.abrsm.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class HttpUtil {


    public static String httpRequest (String requestUrl, String requestMethod, String outputStr) {
        // 创建SSLContext
        StringBuffer buffer = null;
        try {
            URL url = new URL ( requestUrl );
            HttpURLConnection conn = (HttpURLConnection) url.openConnection ();
            conn.setRequestMethod ( requestMethod );
            conn.setDoOutput ( true );
            conn.setDoInput ( true );
            conn.connect ();
            //往服务器端写内容
            if ( null != outputStr ) {
                OutputStream os = conn.getOutputStream ();
                os.write ( outputStr.getBytes ( "utf-8" ) );
                os.close ();
            }
            // 读取服务器端返回的内容
            InputStream is = conn.getInputStream ();
            InputStreamReader isr = new InputStreamReader ( is, "utf-8" );
            BufferedReader br = new BufferedReader ( isr );
            buffer = new StringBuffer ();
            String line = null;
            while ( ( line = br.readLine () ) != null ) {
                buffer.append ( line );
            }
            br.close ();
        } catch ( Exception e ) {
            e.printStackTrace ();
        }
        return buffer.toString ();
    }


}


